package com.hospital.workstation.service.impl;

import cn.hutool.core.annotation.WrappedAnnotationAttribute;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hospital.common.core.domain.entity.SysDictData;
import com.hospital.common.core.domain.entity.SysUser;
import com.hospital.common.utils.StringUtils;
import com.hospital.common.core.page.TableDataInfo;
import com.hospital.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hospital.system.mapper.SysDictDataMapper;
import com.hospital.system.mapper.SysUserMapper;
import com.hospital.workstation.constant.DictConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.hospital.workstation.domain.bo.MedicationAdvisoryBo;
import com.hospital.workstation.domain.vo.MedicationAdvisoryVo;
import com.hospital.workstation.domain.MedicationAdvisory;
import com.hospital.workstation.mapper.MedicationAdvisoryMapper;
import com.hospital.workstation.service.IMedicationAdvisoryService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 用药咨询Service业务层处理
 *
 * @author whb
 * @date 2023-02-21
 */
@RequiredArgsConstructor
@Service
public class MedicationAdvisoryServiceImpl implements IMedicationAdvisoryService {

    private final MedicationAdvisoryMapper baseMapper;
    private final SysDictDataMapper dictDataMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询用药咨询
     */
    @Override
    public MedicationAdvisoryVo queryById(Long id) {
        MedicationAdvisoryVo medicationAdvisoryVo = baseMapper.selectVoById(id);
        // 根据用户ID查询用户信息
        SysUser sysUser = userMapper.selectUserById(medicationAdvisoryVo.getReceiveManId());
        if (ObjectUtil.isNotNull(sysUser)) {
            medicationAdvisoryVo.setReceiveManName(sysUser.getNickName());
        }
        return medicationAdvisoryVo;
    }

    /**
     * 查询用药咨询列表
     */
    @Override
    public TableDataInfo<MedicationAdvisoryVo> queryPageList(MedicationAdvisoryBo bo, PageQuery pageQuery) {
        // 查询类别字典数据
        List<SysDictData> categoryDictDataList = dictDataMapper.selectDictDataByType(DictConstants.ADVISORY_CATEGORY);
        Map<String, String> categoryMap = categoryDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 查询用药咨询列表
        Wrapper<MedicationAdvisory> qw = buildQueryWrapper2(bo);
        Page<MedicationAdvisoryVo> result = baseMapper.customPageList(pageQuery.build(), qw);
        result.getRecords().stream().forEach(medicationAdvisoryVo -> {
            // 设置类别名称
            medicationAdvisoryVo.setCategoryStr(categoryMap.get(medicationAdvisoryVo.getCategory()));
            // 设置是否处理
            medicationAdvisoryVo.setIsDispose((StringUtils.isNotBlank(medicationAdvisoryVo.getDisposeContent()) && ObjectUtil.isNotNull(medicationAdvisoryVo.getDisposeTime())) ? "是" : "否");
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询用药咨询列表
     */
    @Override
    public List<MedicationAdvisoryVo> queryList(MedicationAdvisoryBo bo) {
        LambdaQueryWrapper<MedicationAdvisory> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MedicationAdvisory> buildQueryWrapper(MedicationAdvisoryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MedicationAdvisory> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), MedicationAdvisory::getUserName, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), MedicationAdvisory::getCategory, bo.getCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getAdvisoryContent()), MedicationAdvisory::getAdvisoryContent, bo.getAdvisoryContent());
        lqw.eq(bo.getAdvisoryTime() != null, MedicationAdvisory::getAdvisoryTime, bo.getAdvisoryTime());
        lqw.eq(bo.getReceiveManId() != null, MedicationAdvisory::getReceiveManId, bo.getReceiveManId());
        lqw.eq(bo.getReceiveTime() != null, MedicationAdvisory::getReceiveTime, bo.getReceiveTime());
        lqw.eq(StringUtils.isNotBlank(bo.getDisposeContent()), MedicationAdvisory::getDisposeContent, bo.getDisposeContent());
        lqw.eq(bo.getDisposeTime() != null, MedicationAdvisory::getDisposeTime, bo.getDisposeTime());
        return lqw;
    }

    private Wrapper<MedicationAdvisory> buildQueryWrapper2(MedicationAdvisoryBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<MedicationAdvisory> qw = Wrappers.query();
        qw.like(StringUtils.isNotBlank(bo.getUserName()), "hma.user_name", bo.getUserName())
            .eq(bo.getMedicalRecordNo() != null, "hma.medical_record_no", bo.getMedicalRecordNo())
            .eq(StringUtils.isNotBlank(bo.getCategory()), "hma.category", bo.getCategory())
            .between(params.get("beginDate") != null && params.get("endDate") != null,
                "hma.advisory_time", params.get("beginDate") + " 00:00:00", params.get("endDate") + " 23:59:59");
        return qw;
    }

    /**
     * 新增用药咨询
     */
    @Override
    public Boolean insertByBo(MedicationAdvisoryBo bo) {
        MedicationAdvisory add = BeanUtil.toBean(bo, MedicationAdvisory.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用药咨询
     */
    @Override
    public Boolean updateByBo(MedicationAdvisoryBo bo) {
        MedicationAdvisory update = BeanUtil.toBean(bo, MedicationAdvisory.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MedicationAdvisory entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用药咨询
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
